from importlib import import_module
import subprocess
from robot.api.deco import keyword
import time
import socket


def connect_to_wifi(ssid, password):
    """连接到指定的 Wi-Fi 网络"""
    # 创建一个临时的 Wi-Fi 配置文件
    wifi_config = f"""<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>{ssid}</name>
    <SSIDConfig>
        <SSID>
            <name>{ssid}</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>manual</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>WPA2PSK</authentication>
                <encryption>AES</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            <sharedKey>
                <keyType>passPhrase</keyType>
                <protected>false</protected>
                <keyMaterial>{password}</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>
"""
    config_path = "temp_wifi_config.xml"
    with open(config_path, "w") as f:
        f.write(wifi_config)

    try:
        # 使用 netsh 命令连接到 Wi-Fi
        subprocess.run(
            ["netsh", "wlan", "add", "profile", f"filename={config_path}"], check=True
        )
        subprocess.run(["netsh", "wlan", "connect", f"name={ssid}"], check=True)
        print(f"成功连接到 Wi-Fi: {ssid}")
    except subprocess.CalledProcessError as e:
        print("连接失败：", e)
    finally:
        # 删除临时配置文件
        import os

        if os.path.exists(config_path):
            os.remove(config_path)


@keyword("连接外网")
def connect_to_internet():
    connect_to_wifi(ssid="ZDZX-5G", password="zdzx2501")


@keyword("连接内网")
def connect_to_internal():
    connect_to_wifi(ssid="ccx11111", password="12345678")


if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        function_name = sys.argv[1]
        if function_name == "1":
            connect_to_internet()
        elif function_name == "2":
            connect_to_internal()
        else:
            print(f"Unknown function: {function_name}")
    else:
        print("No function specified")
